const router = require('express').Router();
const jwt = require('jsonwebtoken');
const db = require('./public/db');

const jwtKey = 'wsdd'

router.post('/login', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    db.sql(`select * from Users where UserName = '${req.query.name}' and UserPwd = '${req.query.pass}'`, (err, data) => {
        if (err) res.send({ code: 400, msg: '数据库连接失败' })
        if (data.rowsAffected > 0) {
            let token = jwt.sign({ username: req.query.name }, jwtKey, { expiresIn: '1d' });
            res.send({ code: 200, msg: '登录成功', username: req.query.name, token })
        } else {
            res.send({ code: 401, msg: '登录失败' })
        }
    });
});

router.post('/token', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    let token = req.query.Authorization.split(' ')[1];
    jwt.verify(token, jwtKey, (err) => {
        if (err) res.send({code:403});  
        res.send({code:200});  
    });
})

module.exports = router